import { loginAPI, getUserProfileAPI, getUserInfoAPI } from '@/api/userApi'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { setTimeStamp } from '@/utils/timeStamp'
import { resetRouter } from '@/router'

const actions = {
  /* 用于发送登录请求的action */
  async userLogin(context, loginForm) {
    const loginResult = await loginAPI(loginForm)
    context.commit('setToken', loginResult.data)
    setTimeStamp(Date.now())
    return loginResult.message
  },
  /* 用于退出登录的action */
  userLogout(context) {
    context.commit('clearToken')
    context.commit('clearUserInfo')
    resetRouter()
  },
  /* 用于获取用户基本信息和基本资料的action */
  async fetchUserInfo(context) {
    const { data: profile } = await getUserProfileAPI()
    const { data: userInfo } = await getUserInfoAPI(profile.userId)
    context.commit('setUserInfo', { ...profile, ...userInfo })
    return profile
  }
}
const mutations = {
  /* 设置token的mutation */
  setToken(state, token) {
    // 将token存储于Vuex中(Vuex中存储的数据不是持久化的)
    state.token = token
    // 将token存储于本地存储(持久化存储)
    setToken(token)
  },
  /* 清空token的mutation */
  clearToken(state) {
    // 清空Vuex中的token
    state.token = ''
    // 移除本地持久化存储的token
    removeToken()
  },
  /* 设置用户信息的action */
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  /* 清空用户信息的action */
  clearUserInfo(state) {
    state.userInfo = {}
  }
}
const state = {
  token: getToken() || '',
  userInfo: {}
}
const getters = {}
export default {
  actions,
  mutations,
  state,
  getters,
  namespaced: true
}
